import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'

interface UserInfo {
  name: string
  age: number
}

const AboutView = () => {
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null)
  const [currentTime, setCurrentTime] = useState('')
  let updateInterval: number | null = null

  // 获取全局状态
  const getGlobalState = () => {
    const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
    if (globalState) {
      setUserInfo(globalState.userInfo)
    }
  }

  // 更新当前时间
  const updateCurrentTime = () => {
    const now = new Date()
    setCurrentTime(now.toLocaleTimeString())
  }

  // 设置全局状态变化监听
  const setupGlobalStateListener = () => {
    const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
    if (globalState?.actions) {
      console.log('设置全局状态变化监听器')
      
      // 使用qiankun提供的onGlobalStateChange API监听状态变化
      return globalState.actions.onGlobalStateChange((state: any) => {
        console.log('全局状态变化:', state)
        if (state.userInfo && JSON.stringify(state.userInfo) !== JSON.stringify(userInfo)) {
          setUserInfo({ ...state.userInfo })
        }
      }, true) // true表示立即执行一次回调
    }
    return () => {}
  }

  useEffect(() => {
    console.log('AboutView组件挂载')
    
    // 获取初始状态
    getGlobalState()
    
    // 设置全局状态变化监听
    const cleanup = setupGlobalStateListener()
    
    // 设置定时器更新时间
    updateCurrentTime()
    updateInterval = setInterval(() => {
      updateCurrentTime()
    }, 1000)
    
    // 组件卸载时清理
    return () => {
      // 清理监听器 - 确保cleanup是一个函数
      if (typeof cleanup === 'function') {
        cleanup()
      }
      
      // 清理定时器
      if (updateInterval) {
        clearInterval(updateInterval)
      }
    }
  }, [userInfo])

  // 检查是否在qiankun环境中运行
  const isInQiankun = qiankunWindow.__POWERED_BY_QIANKUN__

  return (
    <div className="about">
      <h2>App3 - About Page</h2>
      
      {/* 只有在独立运行时才显示导航 */}
      {!isInQiankun && (
        <nav>
          <Link to="/app3/home">Home</Link>
          <Link to="/app3/about">About</Link>
        </nav>
      )}
      
      <div className="info-section">
        <h3>从主应用接收的用户信息：</h3>
        <p>用户名：{userInfo?.name}</p>
        <p>年龄：{userInfo?.age}</p>
      </div>
      
      <div className="features">
        <h3>App3 功能特点：</h3>
        <ul>
          <li>✅ 支持独立运行和在qiankun微前端环境中运行</li>
          <li>✅ 使用React框架开发</li>
          <li>✅ 接收主应用传递的用户信息</li>
          <li>✅ 能够向主应用发送更新请求</li>
          <li>✅ 支持与其他子应用共享数据</li>
        </ul>
      </div>
      
      <div className="communication-demo">
        <h3>实时数据同步演示：</h3>
        <p>当前时间：{currentTime}</p>
        <p>如果在其他应用修改了用户信息，这里会自动更新</p>
      </div>
    </div>
  )
}

export default AboutView